package com.haier.cloudremote;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import com.haier.cloudremote.common.SLog;
import com.haier.cloudremote.common.StaticData;
import com.haier.cloudremote.db.DbAdapter;
import com.haier.cloudremote.protocal.CAEProtocal;

import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class FinishActivity extends Activity {

    private static final int TIMER_ONE_SECOND = 10001;
	private Button finishButton;
	private TextView finishTime;
	private int num = 5;
	private boolean isActivityAlive;
	
	private Thread uploadThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.finish);
		
		ActivityStackControlUtil.add(this); 
		
		finishButton = (Button) findViewById(R.id.finish_button);
		finishButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ActivityStackControlUtil.finishProgram();
			}
		});
		finishTime = (TextView) findViewById(R.id.finish_time);
	}


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        for(int i =0; i< 5;i++){
            Message msg = new Message();
            msg.what = i;
            handler.sendMessageDelayed(msg, 5000);
        }

        Timer timer = new Timer();
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                handler.sendEmptyMessage(TIMER_ONE_SECOND);
            }
            
        }, 1000,1000);
        
        isActivityAlive = true;

        uploadStudyList();      
        
    }
	 
	private Handler handler = new Handler(){
	    public void handleMessage(android.os.Message msg) {
	        switch (msg.what){
	            case TIMER_ONE_SECOND:
	                num--;
	                if(num>=0){
	                    finishTime.setText(num+"");
	                }else{
	                    ActivityStackControlUtil.finishProgram();
	                }
	                
	                break;
	            
	                
	        }
	    };
	};

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                return false;

            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}


	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		isActivityAlive = false;
	}

	/**
	 * 上传该地区机顶盒列表
	 */
	private void uploadStudyList() {
		// TODO Auto-generated method stub
		uploadThread = new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				while(isActivityAlive){
					byte isShare = 0x01;
     
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					Date curDate = new Date(System.currentTimeMillis());//获取当前时间    
					String formattime = formatter.format(curDate); //可以获取当前的年月时分,也可以分开写:
					SLog.d("ssc", "updateStudyList--------formattime=="+formattime);
					// 运营商-地域-厂家-型号-版本
					int returnCode = CAEProtocal.uploadStudiedSTB(StaticData.checkedProvince.getPid(), 
							StaticData.checkedCity.getCityId(), 
							StaticData.checkedTown.getTownId(), isShare, 
							"学习-"+StaticData.checkedProvince.getPname()+
							StaticData.checkedCity.getCityName()+
							StaticData.checkedTown.getTownName()+"-"+
							formattime);
					if(returnCode==1001){
//						viewHandler.sendEmptyMessage(SHARE_STUDY_OK);
						break;
					}
					
					try {
						sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						if(e!=null){
							SLog.e("ssc", "FinishActivity-------e.getmessage=="+e.getMessage());
						}
					}
				}
				
				
			}
			
		};
		
		if(needUpload()){
			uploadThread.start();
		}
		
	}

	/**
	 * 是否需要上传
	 * @return
	 */
	private boolean needUpload() {
		// TODO Auto-generated method stub
		boolean isneed = true;
		DbAdapter dbAdapter = new DbAdapter(this);
		dbAdapter.open();
		Cursor cursor = dbAdapter.getAll();
		while (cursor.moveToNext()) {
			int state = cursor.getInt(cursor.getColumnIndex(DbAdapter.F_STATE));
			//如果状态等于0，传过来的是0
			if(state==0){
				isneed = false;
				break;
			}
		}
		dbAdapter.close();
		cursor.close();
		return isneed;
	}	
	
	
}
